import { useState, useEffect, useCallback } from 'react';
import { getSessions, SessionsListRes } from '@/lib/api/session';
import { useAuth } from '@/lib/auth/context';

interface UseInfiniteSessionsOptions {
  pageSize?: number;
  order?: 'asc' | 'desc';
}

export function useInfiniteSessions({ pageSize = 10, order = 'desc' }: UseInfiniteSessionsOptions = {}) {
  const [page, setPage] = useState(1);
  const [allSessions, setAllSessions] = useState<any[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  const { loading: authLoading, user } = useAuth();

  // Get session data
  const fetchSessions = useCallback(async (pageNum: number) => {
    if (!user) return;
    
    try {
      setError(null);
      if (pageNum === 1) {
        setLoading(true);
      } else {
        setIsLoadingMore(true);
      }
      
      const res = await getSessions({ page: pageNum, pageSize, order });
      
      if (pageNum === 1) {
        // First page, set directly
        setAllSessions(res.items);
      } else {
        // Subsequent pages, append to existing list
        setAllSessions(prev => {
          // Avoid duplicate additions
          const existingIds = new Set(prev.map(s => s.id));
          const newItems = res.items.filter(item => !existingIds.has(item.id));
          return [...prev, ...newItems];
        });
      }
      
      // Check if there is more data
      setHasMore(res.items.length === pageSize);
      
    } catch (e: any) {
      setError(e?.message ?? "Loading failed");
    } finally {
      setLoading(false);
      setIsLoadingMore(false);
    }
  }, [user, pageSize, order]);

  // Refetch data when user or parameters change
  useEffect(() => {
    if (authLoading || !user) return;
    fetchSessions(page);
  }, [authLoading, user, page, fetchSessions]);

  // Load more
  const loadMore = useCallback(() => {
    if (!isLoadingMore && hasMore && !loading) {
      setPage(prev => prev + 1);
    }
  }, [isLoadingMore, hasMore, loading]);

  // Reset
  const reset = useCallback(() => {
    setPage(1);
    setAllSessions([]);
    setHasMore(true);
    setIsLoadingMore(false);
    setError(null);
  }, []);

  return {
    sessions: allSessions,
    loading: loading && page === 1, // Only show main loading state when loading first page
    isLoadingMore,
    hasMore,
    error,
    loadMore,
    reset,
  };
}
